package com.example.controller;

import com.example.domain.User;
import com.example.service.UserService;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    UserService userService;

    //查询所有用户
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @ResponseBody
    public String showUsers() {
        List<User> userList = userService.queryAllUser();
        String json = new Gson().toJson(userList);
        return json;
    }


    @RequestMapping(value="/addUser",method = RequestMethod.POST)
    @ResponseBody
    public Map addUser(@RequestBody User user) {
        int flag = userService.addUser(user);
        Map<String, Object> map = new HashMap<String, Object>();
        if (flag == 1) {
            map.put("msg", "新增用户成功");
            return map;
        } else {
            map.put("msg", "新增用户失败");
            return map;
        }
    }

    //    根据用户ID删除用户信息
    @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.DELETE)
    public String dropUser(@PathVariable("id") String id) {
        int flag = userService.dropUser(id);
        if (flag == 1) {
            return "users";
        } else {
            return "error";
        }
    }

    //    根据用户ID查询用户信息
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String queryUser(@PathVariable("id") String id) {
        User user = userService.queryUserById(id);
        String userJson = new Gson().toJson(user);
        return userJson;
    }

    //    根据用户ID来修改用户信息
    @RequestMapping(value="/modifyUser",method = RequestMethod.PUT)
    @ResponseBody
    public Map modifyUser(User user) {
        int flag = userService.modifyUser(user);
        Map<String, Object> map = new HashMap<>();
        if (flag == 1) {
            map.put("msg", "修改用户信息成功");
            return map;
        } else {
            map.put("msg", "修改用户信息失败");
            return map;
        }
    }
}